package cn.zk.question.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * TPC沾包，拆包问题的示例
 *
 */
public class TcpServer {
    private final int port;

    public TcpServer(int port) {
        this.port = port;
    }
    // 服务器的配置
    public void run() throws InterruptedException {
        // boos+worker 线程池组
        EventLoopGroup boos = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            // bootstrapServer
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boos,worker)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            // 自定义handler
                            pipeline.addLast(new TcpServerHandler());
                        }
                    });
            // 启动服务器
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            System.out.println("==>服务器启动成功！");
            // 监听关闭事件
            channelFuture.channel().closeFuture().sync();

        } finally {
            // 关闭两个线程组
            boos.shutdownGracefully().sync();
            worker.shutdownGracefully().sync();
        }
    }

    // 启动群聊服务器
    public static void main(String[] args) throws InterruptedException {
        TcpServer server = new TcpServer(8081);
        server.run();
    }
}
